<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-10-19
 * Time: 上午9:21
 */

namespace common\models\credit_app;


use common\components\tools\Random;
use common\components\tools\Tools;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\web\IdentityInterface;

/**
 * Class Member
 * @package common\models\credit_app
 *
 * @property Branch $branch
 * @property Department $dp
 */
class Member extends \common\models\credit_app_tables\Member implements IdentityInterface
{
    const STATUS_OK = 'ok';
    const U_DP_TYPR_DOT = 'dot';
    const U_DP_TYPR_RG= 'rg';
    const U_DP_TYPR_DP= 'dp';

    public static function getUDpTypes()
    {
        return [
            self::U_DP_TYPR_DOT => '网点人员',
        ];
    }

    public function afterFind()
    {
        parent::afterFind(); // TODO: Change the autogenerated stub
    }

    public static function getLogPath(){
        return \Yii::$app->getRuntimePath().DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'member_import_msg';
    }

    public static function importMembers($data)
    {
        $msg = [];
        $success = 0;
        $failed = 0;
        $member = new self();
        foreach ($data as $k => $v){
            $m = clone $member;
            $m->u_code = $m->uCodeSet($v['u_code']);
            $m->u_realname = $v['u_realname'];
            $m->u_name = $m->uRealNameToName();
            $rnd_pwd = Random::RandomCode(3, 'lower') . Random::RandomCode(3, 'num');
            $m->u_salt = Random::RandomCode(6);
            $m->u_password = md5(md5($rnd_pwd) . $m->u_salt);
            $m->u_role = 5;
            $m->u_dp_type = 'dot';
            $m->u_dp_id = $v['u_dp_id'];
            $m->u_scope = '用户级';
            $m->u_auditlevel = 0;
            $m->u_mobile = (string)$v['u_mobile'];
            $m->u_job = $v['u_job'];
            $m->u_addr = $v['u_addr'];
            $m->u_idcard = $v['u_idcard'];
            $m->u_sex = $v['u_sex'];
            $m->u_birthday = $v['u_birthday'];
            $m->u_culture = '0';
            $m->u_info = $v['u_info'];
            $m->u_bank = (string)$v['u_bank'];
            $m->u_addtime = time();
            $m->u_status = 'ok';
            $m->u_tel= $m->u_qq = $m->u_avatar = "";
            $check_msg = $m->importCheck();
            if ($check_msg=='ok'){
                if ($m->save(false)){
                    $msg[] = ArrayHelper::merge($m->toArray(), ['pwd'=>$rnd_pwd, 'is_save'=>'yes', 'msg'=>'ok']);
                    $success++;
                }else{
                    $msg[] = ArrayHelper::merge($m->toArray(), ['pwd'=>$rnd_pwd, 'is_save'=>'no', 'msg'=>var_export($m->errors, true)]);
                    $failed++;
                }
            }else{
                $msg[] = ArrayHelper::merge($m->toArray(), ['pwd'=>$rnd_pwd, 'is_save'=>'no', 'msg'=>$check_msg]);
                $failed++;
            }
//            break;
        }
        $_msg = var_export($msg, true);
        $log_path = self::getLogPath();
        if (!is_dir($log_path)){
            FileHelper::createDirectory($log_path);
        }
        $log_file = $log_path.DIRECTORY_SEPARATOR.date("Ymd_His").'.log';
        file_put_contents($log_file, $_msg);
        $total = $success+$failed;
        \Yii::$app->session->setFlash('info', "总计数据:{$total};成功:{$success};失败:{$failed};");
    }

    public function importCheck(){
        $msg = 'ok';
        if (self::findOne(['u_name'=>$this->u_name])){
            $msg = "u_name:[{$this->u_name}]已存在";
        }
        if (self::findOne(['u_mobile'=>$this->u_mobile])){
            $msg = "u_mobile:[{$this->u_mobile}]已存在";
        }
        return $msg;
    }

    public function uRealNameToName()
    {
        $u_realname = $this->u_realname;
        $c = mb_strlen($u_realname, 'utf8');
        $arr = array();
        $py = \Yii::$app->pinyin;
        for ($i = 0; $i < $c; $i ++){
            $x = mb_substr($u_realname, $i, 1, 'utf8');
            $x = $py->str2py($x, false);
//            $x = ucfirst($x);
            $arr[] = $x;
        }
        $y = Tools::arr2str($arr, '');
        $name = $y;
        return $name;
    }

    public function uCodeSet($u_code)
    {
        $max_one = self::find()->where(['like', 'u_code', $u_code.'%', false])->orderBy(['u_code'=>SORT_DESC])->one();
        $code = $max_one?substr($max_one->u_code, -4):0;
        $code++;
        $code = str_pad($code,4,"0",STR_PAD_LEFT);
        $code =  $u_code.$code;
        return $code;
    }


    public static function findIdentityByTokenAndUid($token, $uid)
    {
        $t = ApiToken::findOne(['tk_uid'=>$uid]);
        if (!$t){
            throw new ErrorException("yii2work-不存在当前用户API信息(不存在此用户token)", 10010);
        }
        if ($t->tk_token!=$token){
            throw new ErrorException("yii2work-TOKEN信息值错误,当前账号已被登录", 10011);
        }
        if ($t->tk_expiration < time()){
            throw new ErrorException("yii2work-TOKEN已失效，请重新请求", 10012);
        }
        return static::findOne(['u_id' => $uid, 'u_status' => self::STATUS_OK]);
    }

    public static function findIdentityByUNameAndUPassword($u_name, $u_password)
    {
        $m = static::findOne(['u_name' => $u_name, 'u_status' => self::STATUS_OK]);
        if (!$m) {
            throw new ErrorException("没有找到用户！");
        }
        if ($m->u_password!=md5(md5($u_password).$m->u_salt)){
            throw new ErrorException("密码错误！");
        }
        return $m;
    }

    public static function findIdentity($id)
    {
        return static::findOne(['u_id' => $id, 'u_status' => self::STATUS_OK]);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new ErrorException('member 不能直接从token获取，需要有uid！');
    }

    public function getId()
    {
        return $this->u_id;
    }

    public function getAuthKey()
    {
        throw new ErrorException('member 不需要getAuthKey！');
    }

    public function validateAuthKey($authKey)
    {
        throw new ErrorException('member 不需要validateAuthKey！');
    }

    /**
     * @return null|\yii\db\ActiveQuery
     */
    public function getBranch()
    {
        if ($this->u_dp_type == self::DP_TYPE_DOT){
            return $this->hasOne(Branch::class, ['br_id' => 'u_dp_id']);
        }else{
            return null;
        }
    }

    /**
     * @return null|\yii\db\ActiveQuery
     */
    public function getDp()
    {
        if ($this->u_dp_type == self::DP_TYPE_DP){
            return $this->hasOne(Department::class, ['dp_id' => 'u_dp_id']);
        }else{
            return null;
        }
    }
}